const { Client } = require("@notionhq/client")
const dotenv = require("dotenv");

dotenv.config();

const API_URL = 'https://api.guildwars2.com';
const gw2APIUrl: (path: string, token: string) => string = (path: string, token: string) => `${API_URL}${path}?access_token=${token}`

type Currency = {id: number, value: number};

enum GW2Currencies {
  Coin = 1,
  Laurel = 3,
  AstralAclaim = 63
};

async function main() {
    const notion = new Client({
        auth: process.env.NOTION_TOKEN,
    });

    const accounts: any = await notion.databases.query({database_id: process.env.GW2_ACCOUTNS_DB_ID});

    for (let account of accounts.results) {
        if (!account.properties?.['API Key (App)']?.rich_text.length) {
            continue;
        }

        const gw2APIKey = account.properties?.['API Key (App)']?.rich_text?.[0].plain_text;
        console.log(`Account ${account.properties.Name.title[0].plain_text} has API Key (App) ${gw2APIKey}`);
        
        const wallet: Currency[] = (await (await fetch(gw2APIUrl('/v2/account/wallet', gw2APIKey))).json()) as Currency[];

        const gold = Number((wallet.find((currency) => currency.id === GW2Currencies.Coin).value / 10000).toFixed(0));
        const laurels = wallet.find((currency) => currency.id === GW2Currencies.Laurel).value;
        const astralAclaims = wallet.find((currency) => currency.id === GW2Currencies.AstralAclaim).value;        

        console.log(`Updating values for ${account.properties.Name.title[0].plain_text}: 
         - ${gold} gold, 
         - ${laurels} laurels, 
         - ${astralAclaims} AA
        `);

        const response = await notion.pages.update({
          page_id: account.id,
          properties: {
            'Gold': {
              number: gold,
            },
            'Laurels': {
              number: laurels,
            },
            'AA': {
              number: astralAclaims
            },
            'Modified': {
              date: {
                start: new Date(),
                end: null
              }
            }
          },
        });

        console.log(`Updated values for ${account.properties.Name.title[0].plain_text}: 
         - ${response.properties.Gold.number} gold, 
         - ${response.properties.Laurels.number} laurels, 
         - ${response.properties.AA.number} AA
        `)
    }
}

main()
    .then(() => process.exit(0))
    .catch((err) => {
        console.error(err);
        process.exit(1);
    });